package com.simblog.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.mysql.fabric.xmlrpc.base.Params;
import com.simblog.common.constants.Constants;
import com.simblog.oaknt.domain.Article;
import com.simblog.oaknt.domain.Category;
import com.simblog.oaknt.domain.User;
import com.simblog.oaknt.service.IArticleService;
import com.simblog.oaknt.service.ICategoryService;
import com.simblog.oaknt.service.IUserService;
import com.simblog.vo.ArticleCountVo;

@Controller
public class ArticleController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);
	@Reference
	private IArticleService articleService;
	@Reference
	private ICategoryService categoryService;
	@Reference
	private IUserService userService;
	
	
	@RequestMapping(value="p/{userName}")
	public String home(@PathVariable("userName") String userName,PageInfo<Article> pageInfo,Model model,HttpServletRequest request){
		logger.info("跳转到userName={}的个人中心",userName);
		Map<String, Object> params = new HashMap<String,Object>();
		initPage(pageInfo);
		ArticleCountVo articleCountVo = new ArticleCountVo();
		try{
			if(StringUtils.isBlank(userName)){
				return "400";
			}
			User user = userService.selectByUserName(userName);
			if(user == null){
				return "400";
			}
			
			params.put("userId", user.getId());
			User u = getSessionUser(request);
			if(u == null || u.getId().compareTo(user.getId()) != 0){//只能查询公开的文章
				params.put("isPublic", "1");
			}
			pageInfo = articleService.queryPage(params, pageInfo);
		
			getCount(model, params);
		}catch (Exception e) {
			logger.info("跳转到个人主页异常");
			e.printStackTrace();
			return "500";
		}
		
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("userName", userName);
		return "article/list";
	}
	
	@RequestMapping("v/write")
	public String write(HttpServletRequest request,Model model){
		logger.info("跳转到编写文章页面");
		return "article/add";
	}
	
	@ResponseBody
	@RequestMapping("v/insert")
	public JSONObject insert(String title,String categoryId,String tags,String content,String htmlContent,String summary,HttpServletRequest request){
		logger.info("新增文章,title={},categoryId={},tags={},content.length={}",new Object[]{title,categoryId,tags,content.length()});
		Article article = new Article();
		try{
			User user = getSessionUser(request);
			if(StringUtils.isBlank(title)){
				return assemblyJson(null, Constants.RESP_FAIL, "标题不能为空");
			}
			if(StringUtils.isBlank(categoryId)){
				return assemblyJson(null, Constants.RESP_FAIL, "请选择文章分类");
			}
			if(StringUtils.isBlank(tags)){
				return assemblyJson(null, Constants.RESP_FAIL, "请选择文章标签");
			}
			if(StringUtils.isBlank(content)){
				return assemblyJson(null, Constants.RESP_FAIL, "文章正文不能为空");
			}
			if(StringUtils.isBlank(summary)){
				return assemblyJson(null, Constants.RESP_FAIL, "文章概述不能为空");
			}
			
			article.setUserId(user.getId());
			article.setCategoryId(Long.valueOf(categoryId));
			article.setTitle(title);
			article.setTags(tags);
			article.setSummary(summary);
			article.setContent(content);
			article.setHtmlContent(htmlContent);
			article.setIsPublic("1");
			Long id = articleService.insertReId(article);
			
			if(id != null){
				return assemblyJson(id, Constants.RESP_SUCCESS, "文章发布成功");
			}else{
				return assemblyJson(null, Constants.RESP_FAIL, "文章发布失败，稍后再试");
			}
		}catch (Exception e) {
			logger.error("新增文章异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
	@RequestMapping("p/{userName}/detail/{id}")
	public String detail(@PathVariable("userName") String userName,@PathVariable("id") String id,HttpServletRequest request,Model model){
		logger.info("查看文章,userName={},id={}",userName,id);
		Map<String, Object> params = new HashMap<String,Object>();
		try {
			if(StringUtils.isBlank(userName)){
				return "404";
			}
			User user = userService.selectByUserName(userName);
			if(user == null){
				return "404";
			}
			
			User u = getSessionUser(request);
			params.put("id", id);
			if(u == null || u.getId().compareTo(user.getId()) != 0){//只能查询公开的文章
				params.put("isPublic", "1");
			}
			
			List<Article> list = articleService.queryDetail(params);
			if(CollectionUtils.isEmpty(list)){
				return "404";
			}
			
			Article article = list.get(0);
			model.addAttribute("article", article);
		} catch (Exception e) {
			logger.info("查看文章异常");
			e.printStackTrace();
		}
		model.addAttribute("userName", userName);
		return "article/detail";
	}
	
	@RequestMapping("p/{userName}/date/{date}")
	public String queryByTime(@PathVariable("userName")String userName,@PathVariable("date")String date,HttpServletRequest request,Model model,PageInfo<Article> pageInfo){
		logger.info("根据时间归档查询文章列表,userName={},date={}",userName,date);
		initPage(pageInfo);
		Map<String, Object> params = new HashMap<String,Object>();
		try{
			if(StringUtils.isBlank(userName)){
				return "error";
			}
			User user = userService.selectByUserName(userName);
			if(user == null){
				return "404";
			}
			params.put("userId", user.getId());
			params.put("formatDate", date);
			User u = getSessionUser(request);
			if(u == null || u.getId().compareTo(user.getId()) != 0){//只能查询公开的文章
				params.put("isPublic", "1");
			}
			pageInfo = articleService.queryPage(params, pageInfo);
			
			getCount(model, params);
		}catch (Exception e) {
			logger.error("根据时间归档获取文章列表异常");
			e.printStackTrace();
			return "500";
		}
		model.addAttribute("userName", userName);
		model.addAttribute("pageInfo", pageInfo);
		return "article/list";
	}
	
	
	@RequestMapping("p/{userName}/category/{categoryId}")
	public String queryByCategory(@PathVariable("userName")String userName,@PathVariable("categoryId")String categoryId,Model model,HttpServletRequest request,PageInfo<Article> pageInfo){
		logger.info("根据文章分类获取文章列表");
		Map<String, Object> params = new HashMap<String,Object>();
		initPage(pageInfo);
		try{
			if(StringUtils.isBlank(userName)){
				return "error";
			}
			User user = userService.selectByUserName(userName);
			if(user == null){
				return "404";
			}
			params.put("userId", user.getId());
			params.put("categoryId", categoryId);
			User u = getSessionUser(request);
			if(u == null || u.getId().compareTo(user.getId()) != 0){//只能查询公开的文章
				params.put("isPublic", "1");
			}
			pageInfo = articleService.queryPage(params, pageInfo);
			
			getCount(model, params);
		}catch (Exception e) {
			logger.error("根据文章分类获取文章列表异常");
			e.printStackTrace();
			return "500";
		}
		model.addAttribute("userName", userName);
		model.addAttribute("pageInfo", pageInfo);
		return "article/list";
	}
	
	
	//用于查询右侧的文章统计
	public void getCount(Model model,Map<String,Object> params){
		ArticleCountVo articleCountVo = new ArticleCountVo();
		//查询时间统计的数量
		List<Map<String, Object>> timeList = articleService.countByTime(params);
		articleCountVo.setTimeList(timeList);
		//查询分类统计的数量
		List<Map<String, Object>> categoryList = articleService.countByCategory(params);
		articleCountVo.setCategoryList(categoryList);
		model.addAttribute("articleCountVo", articleCountVo);
	}
	
	@RequestMapping("v/article/manage")
	public String manage(Model model,HttpServletRequest request,PageInfo<Article> pageInfo){
		logger.info("文章管理中心");
		Map<String, Object> params = new HashMap<String,Object>();
		initPage(pageInfo);
		try{
			User user = getSessionUser(request);
			params.put("userId", user.getId());
			pageInfo = articleService.queryPage(params, pageInfo);
		}catch (Exception e) {
			logger.error("文章管理中心异常");
			e.printStackTrace();
			return "500";
		}
		model.addAttribute("pageInfo", pageInfo);
		return "article/manage";
	}
	
	
	@RequestMapping("v/edit/{id}")
	public String edit(@PathVariable("id")String id,HttpServletRequest request,Model model){
		logger.info("跳转到修改文章列表");
		Map<String, Object> params = new HashMap<String,Object>();
		try{
			User user = getSessionUser(request);
			params.put("id", id);
			params.put("userId", user.getId());
			
			//查询文章信息
			List<Article> list = articleService.queryDetail(params);
			if(CollectionUtils.isEmpty(list)){//没查到该文章，可能是id有误，或者id对应的文章不属于当前登录的用户
				logger.info("找不到该文章");
				return "404";
			}
			
			//查询分类信息
			params.clear();
			params.put("userId", user.getId());
			List<Category> categoryList = categoryService.queryList(params);
			
			model.addAttribute("categoryList", categoryList);
			model.addAttribute("article", list.get(0));
			return "article/edit";
		}catch (Exception e) {
			logger.error("跳转到修改文章列表中心异常");
			e.printStackTrace();
			return "500";
		}
	}
	
	@ResponseBody
	@RequestMapping("v/update")
	public JSONObject update(Article article,HttpServletRequest request){
		logger.info("更新文章，id={},categoryId={},tags={}",new Object[]{article.getId(),article.getCategoryId(),article.getTags()});
		
		try{
			User user = getSessionUser(request);
			Article temp = articleService.selectByPrimaryKey(article.getId());
			if(temp == null || temp.getUserId().compareTo(user.getId()) != 0){
				return assemblyJson( null, Constants.RESP_FAIL, "行为异常，无效操作");
			}
			article.setUpdateTime(new Date());
			article.setIsDelete(null);
			articleService.updateByPrimaryKeySelective(article);
			
			return assemblyJson(article.getId(), Constants.RESP_SUCCESS, "更新文章成功");
		}catch (Exception e) {
			logger.error("更新文章异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
}
